Skip to content

feat(examples): add metadata-driven grid, form and route proof in TypeScript - #609

Merged
dmealing merged 5 commits into
mainfrom
fm/mo-dynamic-grid-proof
Nov 20, 2026
Merged

dmealing merged 5 commits into
mainfrom
fm/mo-dynamic-grid-proof

Conversation

@dmealing

@dmealing dmealing commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • Adds examples/dynamic-grid, a workspace member that serves every entity from the loaded model: one MetaGrid and one MetaForm component read GET /api/_meta, and one Fastify route mount serves GET/POST/PATCH/PUT/DELETE through ObjectManager on SQLite. Only the types and name constants (entityFile, namesFile) are generated, for hand-written business rules. Model edits reload while the page is open, with no meta gen.
  • Adds the write-up docs/features/metadata-driven-runtime.md, CHANGELOG entries, a README link, and wires the example's test suite into scripts/ci-local.sh and scripts/ci-lane-map.txt.
  • @metaobjectsdev/runtime-ts fixes: mountDeleteRoute now answers 404 {"error":"not_found"} for a missing row instead of 500, by calling ObjectManager.delete with ifMissing: "ignore". The Kysely and Drizzle drivers no longer emit OFFSET without LIMIT (a syntax error on SQLite and MySQL), so an offset alone works. Tests added for both.

Measurement

From docs/features/metadata-driven-runtime.md, produced by bun run measure in the example. It runs the reference generators in memory on the example's own model (5 entities and a value object) and counts both sides with one rule: a line is code when it is not blank and not only a comment.

Metadata-driven path (hand-written once, names no entity) Files Lines of code
Server: one route mount, the list contract, write checks, the model and its schema 6 718
Client: the model reader, <MetaGrid>, <MetaForm> and their controls 9 1108
The mechanism: paid once, whatever the model 15 1826
Generated and kept: types and name constants, which grow with the model 11 390
Generated path (the reference generators, same model) Files Lines of code
entity: types, Zod schemas and the Drizzle table 6 1142
names: name constants 5 104
queries: typed query helpers 5 439
routes: Fastify CRUD routes 5 149
hooks: TanStack Query hooks 10 800
grid: TanStack Table columns 5 188
grid-hook: grid state hook 5 298
form: React form component 5 503
barrel: index.ts 1 6
Total, all of which grows with the model 47 3629

Per entity, the generated path adds about 726 lines in 9.4 files. The metadata-driven path adds about 78 (its types and name constants) and no hand-written code. The two are the same size at about 3 entities; at 50 entities it is about 36,000 generated lines against about 5,700.

Cost of reading metadata at runtime Cost Paid
Server: read and check a list query against the model (two filters, a sort, paging) 1.9 µs per request
Server: ObjectManager.findMany, 1000 rows of 9 columns 6.63 ms (6.6 µs a row) per request
Server: the same SELECT through Kysely with no metadata 1.45 ms (1.5 µs a row) per request
Server: metadata overhead per row (the difference) 5.2 µs per row
Browser: build the client model from /_meta (5.2 KB of JSON) 0.12 ms once per model load
Browser: format 1000 rows of 7 columns from field metadata 0.82 ms (0.8 µs a row) per page drawn
Browser: the same cells as plain String(value) 0.04 ms per page drawn
Browser: metadata overhead per row (the difference) 0.8 µs per row

The sizes are exact. The timings are medians from one developer machine and move with its load: four runs on one day put the server's per-row overhead between 5.2 and 7.7 µs, and a run on the busy validation machine measured 10.4 µs. The "browser" rows were timed in Bun, not in a browser.

Read the sizes with these in mind. Nobody types the generated lines, so the comparison is about how much code exists to review and keep in step with the model. The 1826 lines are hand-written in the example because no package ships them. The two paths are not feature-identical, and the write-up lists what the metadata-driven path cannot do (no compile-time check on the UI or route layer, no browser-side validation from the model, a fixed set of form controls, no projections, reports, single-table inheritance or many-to-many routes, no authorization). It was built and tested on the TypeScript port only; no claim is made that another port has an equivalent, and C# has no ObjectManager for a mount like this to stand on.

Found and not changed here

  • The reference route generator's filter allowlist does not leave out a credential field (view.password) that a model marks @filterable. The example's mount does. The generators were out of scope for this change.
  • ObjectManager reads a numeric key from a path with a lenient number parse, so 0x1, 1e0 and 01 all address row 1 through the packaged route mounts. The example's mount accepts only the plain decimal form. Tightening the shared runtime would change behaviour for existing adopters, so it is left for a separate decision.
  • The CHANGELOG entry quotes 1,823 hand-written lines; the write-up's exact figure after the last review fixes is 1826.

This PR took one no-mistakes gate run.

Validation

Risk Assessment

✅ Low: The change is a self-contained example app, a workspace member that publishes nothing. The shared runtime-ts edits are small: the OFFSET-without-LIMIT workaround in the Kysely and Drizzle drivers, and DELETE now answers 404 for a missing row. Both have tests. I found no defects. The three fix rounds hold up: shortName now returns an unqualified ref whole, routes capture the model once per request, and the source-grep test became a behavioural test.

Testing

Baseline scripts/ci-local.sh --affected --strict-toolchains passed at the target commit and was not re-run. I drove the real bun src/server/main.ts dev server (isolated port 4311, scratch SQLite under a throwaway $DEV_SCRATCH dir) and passed all three scenarios live. Scenario 1: headless Chrome rendered the entity-agnostic grid from /api/_meta (screenshot). Scenario 2: the single route mount served list filter, sort, paging and limit guards, plus create, patch and delete with validation refusals, all as HTTP transcript. Scenario 3: appending a new Warranty entity to the model made /api/warranties serve and accept writes at revision 2 with no restart; a YAML syntax break and removing an entity that holds rows were both refused, and the server kept serving the prior revision. I restored the model file (git status clean) and stopped the server process group. The example's own focused suite (bun test in examples/dynamic-grid) passed 122/122 and covers the review fixes (packageless-model shortName, single model capture per request, source-grep test removed). Those fixes were not re-run red-before-fix and the packageless path is in-process, not live. Note: after the refused revert the server kept revision 4 (with Warranty) while the worktree file was clean, which is the documented refuse-and-keep behavior, not a defect.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Page renders an entity-agnostic grid from the served model (headless Chrome against the live dev server, synthetic seed data) ✅ pass live dynamic-grid-page.png; Chrome --headless=new --screenshot of http://127.0.0.1:4311/
Single route mount serves list, filter, sort, paging, create, update, delete and rejects bad input from the loaded model (curl against live server, synthetic rows) ✅ pass live dynamic-grid-api-transcript.txt
Adding an entity to the model edit serves it live; broken or data-losing edits are refused while the prior revision keeps serving (adversarial, edits to a temp-modified model file restored afterwards) ✅ pass live dynamic-grid-server.log; dynamic-grid-api-transcript.txt

Headless Chrome screenshot of the metadata-driven grid page (Customer grid, nav built from /api/_meta)

Evidence: Live API transcript: list, filter, sort, paging guards, write validation, PATCH, DELETE
# dynamic-grid live API transcript (dev server 127.0.0.1:4311, synthetic seed + synthetic Warranty entity)

$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/../api/_served
{"revision":4,"collections":{"Customer":"customers","Technician":"technicians","Part":"parts","WorkOrder":"work_orders","WorkOrderLine":"work_order_lines","Warranty":"warranties"},"pagination":{"defaultLimit":10,"maxLimit":50}} HTTP 200


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?limit=2
[{"id":1,"name":"Harbor Bakery","email":"ops@harborbakery.example","tier":"gold","active":true,"billingAddress":{"street":"12 Quay Street","city":"Portside","postalCode":"04101"}},{"id":2,"name":"Lakeside Cycles","email":"hello@lakesidecycles.example","tier":"standard","active":true,"billingAddress":{"street":"88 Shore Road","city":"Lakeside"}}] HTTP 200


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?filter[tier][eq]=gold
[{"id":1,"name":"Harbor Bakery","email":"ops@harborbakery.example","tier":"gold","active":true,"billingAddress":{"street":"12 Quay Street","city":"Portside","postalCode":"04101"}}] HTTP 200


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?filter[tier][in]=gold,platinum&sort=name:desc
[{"id":3,"name":"Northgate Print","email":null,"tier":"platinum","active":true,"billingAddress":{"street":"3 Mill Lane","city":"Northgate","postalCode":"03301"}},{"id":1,"name":"Harbor Bakery","email":"ops@harborbakery.example","tier":"gold","active":true,"billingAddress":{"street":"12 Quay Street","city":"Portside","postalCode":"04101"}}] HTTP 200


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?limit=999
{"error":"limit_too_large","maxLimit":50} HTTP 400


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?sort=nope
{"error":"invalid_sort","field":"nope","expected":"sort=<field>:asc|desc","allowed":["name","email","tier","active"]} HTTP 400


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?filter[tier][regex]=g
{"error":"invalid_filter_op","field":"tier","op":"regex","allowed":["eq","ne","in","like","isNull"]} HTTP 400


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?filter[name][like]=%25Harb
{"error":"filter.leading_wildcard_disallowed","field":"name"} HTTP 400


$ curl -g -s -w '%{http_code}' http://127.0.0.1:4311/api/customers?filter[tier][eq]=bogus
{"error":"invalid_filter_value","field":"tier","op":"eq","expected":"one of standard, gold, platinum","allowed":["standard","gold","platinum"]} HTTP 400


$ POST valid customer
{"id":6,"name":"Validate Co","email":"v@x.example","tier":"platinum","active":true,"billingAddress":{"street":"1 Test St","city":"Testville"}} HTTP 201
$ POST bad enum
{"error":"validation","issues":[{"path":["tier"],"code":"enum","message":"'tier' must be one of standard, gold, platinum."}]} HTTP 400
$ POST missing required
{"error":"validation","issues":[{"path":["name"],"code":"required","message":"'name' is required"}]} HTTP 400
$ POST unknown field
{"error":"unknown_fields","fields":["sqlInjection"]} HTTP 400
$ PATCH id 5 tier gold
{"error":"not_found"} HTTP 404
$ DELETE id 5
HTTP 404
$ GET id 5 after delete
{"error":"not_found"} HTTP 404
Evidence: Dev server log: live reload accepted, YAML break refused, drop-table refused, revisions
dynamic grid demo: http://127.0.0.1:4311  (API under http://127.0.0.1:4311/api, model at http://127.0.0.1:4311/api/_meta)
watching {run-worktree}/examples/dynamic-grid/metaobjects, {run-worktree}/examples/dynamic-grid/.metaobjects
model reloaded: revision 2, 6 entities
reload refused, still serving revision 2:
ParseError: Invalid YAML: Flow sequence in block collection must be sufficiently indented and end with a ] at line 188, column 1:

        name: [unclosed

^

model reloaded: revision 3, 6 entities
reload refused, still serving revision 3:
ParseError: dataGrid layout "default" on entity "Warranty" has @defaultSortField "code" but no such field exists on "Warranty". Available fields: id, active
model reloaded: revision 4, 6 entities
reload refused, still serving revision 4:
BlockedChangesError: 1 blocked change(s):
  - drop-table on warranties: pass allow.dropTable
Evidence: Focused example suite run (bun test, 122 pass)
bun test v1.3.14 (0d9b296a)

 122 pass
 0 fail
 580 expect() calls
Ran 122 tests across 9 files. [12.95s]

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (2) ✅
  • ⚠️ examples/dynamic-grid/test/app.test.tsx:139 - New test src/client mentions no entity, field or collection of the demo model reads every src/client/*.ts(x) file with readFileSync, strips comments by regex, and regex-matches entity/field names in the source text. This is a source-content-only assertion: it proves nothing about rendered behavior, and it has false positives and negatives (a name built from string parts, a name in a template literal, a comment-like string). The repo test-quality rule forbids this pattern. The behavior it stands for (no component names an entity) is already shown by the other tests, which render a metadata edit (a new entity, a changed enum) with no code change (live-reload.test.ts, the add-an-entity test in app.test.tsx). Remove it, or replace it with a behavioral test that loads a model whose entity and field names are all new and asserts the grid, form and routes serve it.
  • ℹ️ examples/dynamic-grid/src/server/routes.ts:289 - Member GET and DELETE read the model twice per request: memberAt calls model() for the entity, then the handler calls model().om again. A reload between the two calls pairs an entity from revision N with the ObjectManager of N+1. If the reload removed that entity, om.findById or om.delete throws and the request answers a redacted 500 instead of 404. The window is tiny, but the list, create and update handlers already capture const current = model() once. Do the same in the GET-by-id handler (line 289) and the DELETE handler (line 334), and have memberAt take the captured model.

🔧 Fix applied.
1 warning still open:

  • ⚠️ examples/dynamic-grid/src/client/model.ts:167 - shortName returns the wrong name for an unqualified reference. When the ref has no ::, ref.lastIndexOf(&#39;::&#39;) is -1 and the includes guard adds 0, so the code runs ref.slice(-1) and returns the last character. shortName(&#34;Customer&#34;) is &#34;r&#34;, and shortName(&#34;Customer.id&#34;) is &#34;d&#34;. I confirmed that metaJson on a packageless model emits @objectRef: &#34;Addr&#34; unqualified. The demo model declares package: demo::workshop, so its refs are qualified and the tests pass. For a model without a package, the client silently gets no value object (the field.object renders as 'no control' and the grid cell falls back to JSON), no references (foreign keys become plain integer inputs and cells show raw ids), and no related lists. Nothing errors. The README tells readers to edit the model and copy the approach. Same defect at every call site: model.ts:199 (valueObjectName), model.ts:217 (references), model.ts:263 (relatedModels target match). Fix: compute the start index from lastIndexOf only when the separator is present (const at = ref.lastIndexOf(SEP); const bare = at &lt; 0 ? ref : ref.slice(at + SEP.length)), and add a test that loads a packageless model.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Page renders an entity-agnostic grid from the served model (headless Chrome against the live dev server, synthetic seed data) ✅ pass live dynamic-grid-page.png; Chrome --headless=new --screenshot of http://127.0.0.1:4311/
Single route mount serves list, filter, sort, paging, create, update, delete and rejects bad input from the loaded model (curl against live server, synthetic rows) ✅ pass live dynamic-grid-api-transcript.txt
Adding an entity to the model edit serves it live; broken or data-losing edits are refused while the prior revision keeps serving (adversarial, edits to a temp-modified model file restored afterwards) ✅ pass live dynamic-grid-server.log; dynamic-grid-api-transcript.txt
  • scripts/ci-local.sh --affected --strict-toolchains
  • scripts/ci-local.sh --affected --strict-toolchains (baseline, already passed at target commit, not re-run)
  • PORT=4311 bun src/server/main.ts in examples/dynamic-grid with DEV_SCRATCH isolated (live dev server)
  • curl -g list/filter/sort/paging/CRUD/validation against /api/customers, /api/technicians, /api/work_orders, /api/warranties
  • Model append of Warranty entity to metaobjects/meta.workshop.yaml with reload observed via /api/_served revision 2
  • Broken YAML append to model: reload refused, revision kept (server.log)
  • Removing Warranty entity with rows: refused by drop-table guard, revision kept (server.log); model restored via git checkout
  • google-chrome --headless=new --screenshot of http://127.0.0.1:4311/
  • bun test in examples/dynamic-grid (122 pass, 0 fail) with DEV_SCRATCH set to a throwaway scratch directory
  • Server stopped by process group (TERM to pgid); scratch dir removed
⚠️ **Document** - 1 info
  • ℹ️ Timing figures in docs/features/metadata-driven-runtime.md (Cost of reading metadata at runtime) not refreshed. One measure run here gave server metadata overhead 10.4 us/row (doc: 5.2 us, range 5.2-7.7 us over four runs) and browser 1.7 us/row (doc: 0.8 us). The doc says timings move with the machine and the review fixes did not touch hot paths, so the documented figures were kept. A re-run of four timings on a quiet machine would settle the current range.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…ypeScript

examples/dynamic-grid serves and renders every entity of a model from the
metadata loaded at runtime, with no code generated per entity:

- <MetaGrid entity="..."/> and <MetaForm entity="..."/> take an entity name
  and read columns, types, labels, enum members, relationships, validation
  limits, filter operators and sort from GET /_meta. They reuse EntityGrid,
  CurrencyInput and the filter query builder from the web client packages.
- One Fastify mount serves list, get, create, update and delete for every
  entity through ObjectManager, on SQLite, with the wire contract of the
  generated routes: filter and sort allowlists from the model, typed filter
  values, bound parameters only, unknown-field 400, api.pagination, and no
  credential field read or written.
- The only generated code is the types and name constants; the hand-written
  business rules are typed against them.
- Editing the metadata file reloads the model: the grid, the form and the
  API change with no regeneration. A change that would lose data is refused.

docs/features/metadata-driven-runtime.md measures it against the reference
generators on the same five-entity model (1,781 hand-written lines paid
once, against 3,629 generated lines that grow by about 726 an entity),
gives the per-row cost of the metadata lookups, and lists what the approach
cannot do. It is a TypeScript example, not a package, and claims no
equivalent in the other ports.

Also fixes mountCrudRoutes and mountDeleteRoute in runtime-ts, which
answered 500 for DELETE on a missing row; they answer 404 now.

The example's suite runs in the ts-unit lane, and the lane map sends a
change under examples/dynamic-grid to the TypeScript lanes only.
Review of the example found nine defects; each is fixed with a test.

Example (examples/dynamic-grid):
- A credential (view.password) can no longer be filtered or sorted on,
  even when the model marks it @filterable. A like filter on a hidden
  value would read it out a prefix at a time.
- A whole-number key is addressed by its plain decimal form only; 0x1,
  1e0 and 01 are 404, not row 1.
- Every list is ordered by the caller's sort and then the primary key,
  so rows that tie on the sort do not move between pages.
- Model reloads run one at a time, and a schema change is applied by the
  migration engine's transactional applier, so one that fails part-way
  changes nothing. A runtime that cannot load removes its scratch files.
- A business rule sees the model's defaults on create and the stored row
  on update; the stock rule no longer re-judges a line whose part and
  quantity did not change.
- The grid keeps a reference title that arrives after the page was
  fetched again, and a field the caller's `where` fixes is not offered in
  the filter bar and cannot be overridden by a filter.

Runtime (@metaobjectsdev/runtime-ts):
- findMany with an offset and no limit was a SQL syntax error on SQLite
  and MySQL in the Kysely and Drizzle drivers. An offset alone now
  carries a limit no result can reach.

Then a simplification pass: one isRecord a side, typed route params, the
credential field list looked up once a list instead of once a row, rows
and count fetched together. The write-up's size and timing tables are
re-measured.
@dmealing
dmealing merged commit 42ed1d2 into main Nov 20, 2026
10 checks passed
@dmealing
dmealing deleted the fm/mo-dynamic-grid-proof branch November 20, 2026 01:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant